<template>
  <div class="pptist-editor" id="ppt">
    <EditorHeader class="layout-header" @show="showQuotation" @saveModule="saveModule" />
    <div class="layout-content">
      <Thumbnails class="layout-content-left" />
      <div class="layout-content-center">
        <CanvasTool class="center-top" />
        <Canvas class="center-body" :style="{ height: `calc(100% - ${remarkHeight + 40}px)` }" />
        <Remark class="center-bottom" v-model:height="remarkHeight" :style="{ height: `${remarkHeight}px` }" />
      </div>
      <Toolbar class="layout-content-right" id="ppt-des-4" @show="showQuotation" @saveModule="saveModule" />
    </div>
  </div>

  <SelectPanel v-if="showSelectPanel" />
  <SearchPanel v-if="showSearchPanel" />
  <NotesPanel v-if="showNotesPanel" />

  <Modal :visible="!!dialogForExport" :width="680" @closed="closeExportDialog()">
    <ExportDialog />
  </Modal>
  <SelectQuotationForm ref="selectQuotationFormRef" @ok="selectQuotationOk" @loading="spin"></SelectQuotationForm>
  <PPTAddForm ref="pptAddFormRef"></PPTAddForm>
  <FullscreenSpin :loading="loading" :tip="tip" />
</template>

<script lang="ts" setup>
import { ElMessage } from 'element-plus';
import { ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useMainStore } from '@/components/PPTist/store'
import useGlobalHotkey from '@/components/PPTist/hooks/useGlobalHotkey'
import usePasteEvent from '@/components/PPTist/hooks/usePasteEvent'

import EditorHeader from './EditorHeader/index.vue'
import Canvas from './Canvas/index.vue'
import CanvasTool from './CanvasTool/index.vue'
import Thumbnails from './Thumbnails/index.vue'
import Toolbar from './Toolbar/index.vue'
import Remark from './Remark/index.vue'
import ExportDialog from './ExportDialog/index.vue'
import SelectPanel from './SelectPanel.vue'
import SearchPanel from './SearchPanel.vue'
import NotesPanel from './NotesPanel.vue'
import Modal from '@/components/PPTist/components/Modal.vue'
import SelectQuotationForm from '@/views/goods/quotation/modules/selectQuotationForm.vue'
import PPTAddForm from '@/views/goods/template/modules/addForm.vue'
import { useSlidesStore } from '@/components/PPTist/store'
import FullscreenSpin from '@/components/PPTist/components/FullscreenSpin.vue'
import { randomUUID } from '@/utils/util'
import { ToolbarStates } from '@/components/PPTist/types/toolbar'

import '@/components/PPTist/assets/styles/global.scss'
import { handleIntroJs } from '@/utils/util'
import { getMaterialPpt } from '@/api/goods/materialPpt';

import { AxiosPromise } from 'axios';
import { QuotationVO } from '@/api/goods/quotation/types';
const mainStore = useMainStore()
const { dialogForExport, showSelectPanel, showSearchPanel, showNotesPanel, activeElementIdList } = storeToRefs(mainStore)
const closeExportDialog = () => mainStore.setDialogForExport('')


const route = useRoute();
const loading = ref(false)
const tip = computed(() => '加载数据中...')
const { slides, hasRendered } = storeToRefs(useSlidesStore())
const slidesStore = useSlidesStore()
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
console.log('proxy :>> ', proxy);
const remarkHeight = ref(40)
const showQuotation = () => {
  proxy.$refs.selectQuotationFormRef.show()
}
const selectQuotationOk = (info: any) => {
  mainStore.setQuotationInfo(info)
  resetSelides(info)
}
const resetSelides = (info: any) => {
  if (hasRendered.value) {
    loading.value = false
    ElMessage.error('关联失败：仅允许关联一次')
    return
  }
  slidesStore.setRender(true)
  // 重置slides
  let newSlides = []
  slides.value.forEach(async (slide: any) => {
    if (!slide.isDynamic) {
      newSlides.push(slide)
    } else {
      (info.quotationItemVoList || []).forEach(val => {
        newSlides.push({
          ...slide,
          id: slide.id + randomUUID(),
          elements: slide.elements.map((element: any) => {
            if (element.keyStr) {
              let pattern = />([^<]+)</g
              let bodyString = element.content.replace(pattern, `>${(element.keyTitle || '') + '' + val.jzgGoodsVo[element.keyStr]}<`)
              return {
                ...element,
                content: bodyString
              }
            }
            return element
          })
        })
      });
    }
  })
  // 重置数据
  slidesStore.setSlides(newSlides)
  loading.value = false
}
const saveModule = () => {
  // mainStore.saveModule()
  if (slidesStore.templateId) {
    proxy.$refs.pptAddFormRef.edit({
      ...slidesStore.templateInfo,
      remark: JSON.stringify(slides.value)
    })
  } else {
    proxy.$refs.pptAddFormRef.add({ remark: JSON.stringify(slides.value) })
  }

}
const spin = (bol: boolean) => {
  loading.value = bol
}
if (route.query.id) {
  console.log('route :>> ', route.query.id);
  getMaterialPpt(route.query.id).then(res => {
    if (res.code == 200) {
      const data: any = res.data
      slidesStore.setSlidesInfo(data)
    }
  })
} else {
  // 清空模板数据
  // slidesStore.setSlidesInfo({
  //   templateId: '',
  //   templateInfo: {
  //     groupId: '',
  //     pptName: '',
  //     remark: ''
  //   }
  // })
}
onMounted(() => {
  const pptIntor = localStorage.getItem('pptIntor')
  if (!pptIntor) {

    handleIntroJs('ppt', 1, (obj) => {
      if (obj.id === 'ppt-des-2') {
        slidesStore.updateSlideIndex(1)
        const activeElement = slides.value[1].elements.find(v => v.type === 'text').id
        mainStore.setActiveElementIdList([activeElement])
        mainStore.setToolbarState(ToolbarStates.EL_KEYSTR)
      }
      if (obj.id === 'ppt-des-5') {
        localStorage.setItem('pptIntor', 'true')
      }
    })
  }
}),
  useGlobalHotkey()
usePasteEvent()
</script>

<style lang="scss" scoped>
.pptist-editor {
  height: 100vh;
}

.layout-header {
  height: 40px;
}

.layout-content {
  height: calc(100% - 40px);
  display: flex;
}

.layout-content-left {
  width: 160px;
  height: 100%;
  flex-shrink: 0;
}

.layout-content-center {
  width: calc(100% - 160px - 320px);

  .center-top {
    height: 40px;
  }
}

.layout-content-right {
  width: 320px;
  height: 100%;
}
</style>